﻿using UnityEngine;
using UniRx;
using System;

public static partial class Extensions
{
    public static IDisposable SubscribeLog<T>(this IObservable<T> source)
    {
        return source.Subscribe(
            _ => Debug.Log($"[{Time.time}] UniRx Logger: next"),
            _ => Debug.LogError($"[{Time.time}] UniRx Logger: error"),
            () => Debug.LogWarning($"[{Time.time}] UniRx Logger: complete")
        );
    }

    public static IObservable<T> WhenActive<T>(this IObservable<T> source, GameObject gameObject)
    {
        return source.Where(_ => gameObject.activeInHierarchy);
    }

    public static IObservable<T> WhenActive<T>(this IObservable<T> source, MonoBehaviour comp)
    {
        return source.Where(_ => comp.gameObject.activeInHierarchy && comp.isActiveAndEnabled);
    }

    public static IObservable<bool> ToBool(this IObservable<long> source)
    {
        return source.Select(val => val == 0);
    }

    public static IObservable<bool> ToBool(this IObservable<float> source, float threshold)
    {
        return source.Select(val => {
            if (threshold < 0) threshold = -threshold;
            return val <= threshold && val >= -threshold;
        });
    }

    public static IObservable<float> ToFloat(this IObservable<long> source)
    {
        return source.Select(val => (float)val);
    }

    public static IObservable<float> ToFloat(this IObservable<bool> source)
    {
        return source.Select(val => val ? 1f : 0f);
    }
}